package com.cmcc.groupcontacts.firewall.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.ValidationUtil;
import com.yinhai.activity.R;

/**
 * 
 * Adapter抽象基类
 * 
 * @author 
 * 
 */
public abstract class BaseAdapter<T> extends ArrayAdapter<T> {
	protected LayoutInflater inflater;
	protected Integer layoutResoureId;
	protected List<T> dataSource;

	public void setLayoutResoureId(Integer layoutResoureId) {
		this.layoutResoureId = layoutResoureId;
	}

	public List<T> getDataSource() {
		return this.dataSource;
	}

	public void setDataSource(List<T> dataSource) {
		if (this.dataSource == null) {
			this.dataSource = new ArrayList<T>();
		} else {
			this.dataSource.clear();
		}
		
		if (dataSource == null) {
			this.dataSource = null;
		} else {
			this.dataSource.addAll(dataSource);
		}
		notifyDataSetChanged();
	}

	public T getItem(int position) {
		if (ValidationUtil.isNullOrEmpty(dataSource) || dataSource.size() <= position) {
			return null;
		} else {
			return dataSource.get(position);
		}
	}

	public BaseAdapter(Context context, List<T> objects) {
		this(null, context, objects);
	}

	public BaseAdapter(Integer layoutResoureId, Context context, List<T> objects) {
		super(context, 0, objects);
		this.layoutResoureId = layoutResoureId;
		inflater = LayoutInflater.from(context);
		this.dataSource = objects;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		try {
			convertView = cacheView(position, convertView, parent);
			setValueByViewCache(convertView, position);
			return convertView;
		} catch (Exception e) {
			ExceptionHandler.handle(e);
			return null;
		}
	}

	/**
	 * 缓存列表行视图，可由子类重载自定义
	 * 
	 * @param position
	 * @param convertView
	 * @param parent
	 * @return
	 */
	protected View cacheView(int position, View convertView, ViewGroup parent) {
		if (ValidationUtil.isNullOrZero(layoutResoureId)) {
			String layoutResIdNotNull = getContext().getString(R.string.layout_resourceid_not_null);
			throw new AdapterException(layoutResIdNotNull);
		}

		if (convertView == null || convertView.getTag() == null) {
			convertView = inflater.inflate(this.layoutResoureId, null);
			setViewCache(convertView, position);
		} else {
			getViewCache(convertView, position);
		}

		return convertView;
	}

	/**
	 * 缓存布局视图中的控件
	 * 
	 * @param convertView
	 */
	protected abstract void setViewCache(View convertView, int position);

	/**
	 * 获取已缓存的布局视图中的控件
	 * 
	 * @param convertView
	 */
	protected abstract void getViewCache(View convertView, int position);

	/**
	 * 从视图缓存中加载数据
	 * 
	 * @param position
	 */
	protected abstract void setValueByViewCache(View convertView, int position);
}
